package com.longrise.android.byjk.plugins.login;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.advertisement.admanager.ADManager;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.datasource.remote.ReloginBean;
import com.longrise.common.utils.DZZWTools;
import com.umeng.analytics.MobclickAgent;


/**
 * Created by callxkj on 2016/12/16.
 * 处理登录 注册 自动登录数据
 * 1,注册 2,登录 3,手机号注册 4,手机号登录 5,启动页自动登录 6,引导页自动登录
 */

public class UserController {
    private static final String TAG = "UserController";
    private static UserController mInstance;
    private String mPassword;
    public static final int REGIST = 1;
    public static final int LOGIN = 2;
    public static final int REGIST_BYPHONE = 3;
    public static final int LOGIN_BYPHONE = 4;
    public static final int LAUNCH = 5;
    public static final int GUIDE = 6;

    private UserController() {

    }

    public static UserController getInstance() {
        if (mInstance == null) {
            mInstance = new UserController();
        }
        return mInstance;
    }

    /**
     * 登录
     */
    public void login(final int flag, final Context context, final EntityBean requestBean, final UserCallback callback) {
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_sUserLogin", requestBean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                EntityBean bean = requestBean.getBean("bean");
                mPassword = bean.getString("password");
                parseLoginData(flag, context, result, requestBean, callback);
            }

            @Override
            public void onFinished(String key, String service) {
                callback.onFinish();
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                callback.onFail(context.getString(R.string.nonetwork));
            }
        });
    }

    /**
     * 注册
     */
    public void regist(final Context context, final EntityBean bean, final UserCallback callback) {
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_iUserReg", bean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                EntityBean rbean = bean.getBean("bean");
                mPassword = rbean.getString("signpwd");
                parseLoginData(1, context, result, bean, callback);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                callback.onFail(context.getString(R.string.networkerror));
            }

            @Override
            public void onFinished(String key, String service) {
                callback.onFinish();
            }
        });
    }

    /**
     * 通过手机号注册
     *
     * @param mobile     手机号
     * @param mobilecode 短信验证码
     */
    public void mobileRegist(final Context context, String mobile, String mobilecode, final UserCallback callback) {
        final EntityBean bean = new EntityBean();
        bean.set("mobile", mobile);
        bean.set("mobilecode", mobilecode);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_iUserRegByMobile", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                mPassword = "";
                parseLoginData(3, context, result, bean, callback);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                callback.onFail(context.getString(R.string.networkerror));
            }

            @Override
            public void onFinished(String key, String service) {
                callback.onFinish();
            }
        });
    }

    /**
     * @param mobile     手机号
     * @param mobilecode 手机验证码
     */
    public void mobileLogin(final Context context, String mobile, String mobilecode, final UserCallback callback) {
        final EntityBean bean = new EntityBean();
        bean.set("mobile", mobile);
        bean.set("mobilecode", mobilecode);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_sUserLoginByMobile", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                mPassword = "";
                parseLoginData(4, context, result, bean, callback);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                callback.onFail(context.getString(R.string.networkerror));
            }

            @Override
            public void onFinished(String key, String service) {
                callback.onFinish();
            }
        });
    }

    /**
     * 用手机号码注册登录 自动登录
     */
    private void setPhoneLoginMessage(Context context, String username, String password) {
        final EntityBean bean1 = new EntityBean();
        bean1.set("username", username);
        bean1.set("password", password);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean1);
        setReLoginMessage(context, fbean);
    }

    /**
     * 注册后保存 自动登录的bean
     */
    private void setRegistRelogin(Context context, EntityBean requestBean) {
        try {
            EntityBean bean = requestBean.getBean("bean");
            String usersfzh = bean.getString("usersfzh");
            String signpwd = bean.getString("signpwd");
            final EntityBean bean1 = new EntityBean();
            bean1.set("username", usersfzh);
            bean1.set("password", signpwd);
            EntityBean fbean = new EntityBean();
            fbean.set("bean", bean1);
            setReLoginMessage(context, fbean);
        } catch (Exception e) {

        }
    }


    /**
     * 保存sessionid
     * 并且本地实例化
     */
    private void setReLoginMessage(Context context, EntityBean requestBean) {
        ReloginBean requsetInfo = new ReloginBean();
        requsetInfo.setBean(requestBean);
        requsetInfo.setKey(null);
        requsetInfo.setServiceName("bbt_login_sUserToken");
        requsetInfo.setServiceUrl(UrlConstants.BaseUrl);
        requsetInfo.setTime(System.currentTimeMillis());
        LoadDataManager.getInstance().setReloginBean(requsetInfo);
    }


    /**
     * 解析登陆请求返回的结果
     * flag: 1,注册 2,登录 3,手机号注册 4,手机号登录 5,启动页自动登录
     *
     * @param result
     */
    private void parseLoginData(int flag, Context context, Object result, EntityBean requestBean, UserCallback callback) {
        try {
            DZZWTools.dismissDialog(null);
            if (result != null) {
                EntityBean bean = (EntityBean) result;
                String resultdesc = (String) bean.get("resultdesc");
                int resultstate = (Integer) bean.get("resultstate");
                if (resultstate == 1) { // 登录成功

                    EntityBean resultbean = bean.getBean("result");
                    if (requestBean == null) {
                        callback.onFail(resultdesc);
                        return;
                    }
                    UserInfor userInfor = UserInfor.getInstance();
                    String userheadurl = (String) resultbean.get("userheadurl"); // 用户头像
                    userInfor.setUserHeadIcon(userheadurl);

                    String username = (String) resultbean.get("username"); // 用户姓名
                    userInfor.setUserName(username);

                    String usersfzh = (String) resultbean.get("usersfzh"); // 身份证号
                    userInfor.setUsersfzh(usersfzh);

                    String userphone = (String) resultbean.get("userphone"); // 手机号码
                    userInfor.setUserphone(userphone);

                    String userworkarea = (String) resultbean.get("userworkarea"); // 工作地区
                    userInfor.setUserworkareaname(userworkarea);

                    String usercomp = (String) resultbean.get("usercomp"); // 工作机构
                    userInfor.setUsercomp(usercomp);

                    String wenxinstatus = resultbean.getString("wenxinstatus"); // 是否绑定微信
                    userInfor.setWenxinstatus(wenxinstatus);

                    String userid = (String) resultbean.get("userid"); // 用户id
                    userInfor.setUserid(userid);

                    String personname = (String) resultbean.get("personname"); // 真实姓名
                    userInfor.setPersonname(personname);

                    String weixinnickname = resultbean.getString("weixinnickname");
                    userInfor.setWeixinnickname(weixinnickname);

                    String isrealcardno = resultbean.getString("isrealcardno"); //sfzh是否真的为身份证号
                    userInfor.setIsRealCardNo(isrealcardno);

                    //证件类型
                    String cardtype = resultbean.getString("cardtype");
                    userInfor.setCardtype(cardtype);

                    //证件类型名称
                    String cardtypename = resultbean.getString("cardtypename");
                    userInfor.setCardtypename(cardtypename);

                    //vip相关
                    EntityBean vipinfoBean = resultbean.getBean("vipinfo");
                    //vip状态
                    Integer vipstate = vipinfoBean.getInt("vipstate");
                    userInfor.setVipstate(vipstate);
                    //会员类型
                    Integer viptype = vipinfoBean.getInt("viptype");
                    userInfor.setViptype(viptype);
                    //会员类型名称
                    String viptypename = vipinfoBean.getString("viptypename");
                    userInfor.setViptypename(viptypename);
                    //截止日期
                    String deadline = vipinfoBean.getString("deadline");
                    String[] split = deadline.split(" ");
                    userInfor.setDeadline(split[0].replace("-", "/"));
                    //剩余天数
                    Integer remainingdays = vipinfoBean.getInt("remainingdays");
                    userInfor.setRemainingdays(remainingdays);


                    //sjz加入 2016-12-15  个人资料
                    userInfor.setUserNickName(resultbean.getString("nickname"));  //昵称
                    userInfor.setUserZYXX(resultbean.getString("certtype"));      //执业证
                    userInfor.setUserProfile(resultbean.getString("profile"));    //个人简介
                    userInfor.setUserCPZS(resultbean.getString("productname"));   //产品展示
                    userInfor.setIsauthorised(resultbean.getBoolean("isauthorised"));

                    //2018-3-9 个人资料
                    userInfor.setUserGRRY(resultbean.getString("honordesc"));   //个人荣誉
                    userInfor.setIsecardvip(resultbean.getString("isecardvip"));   //是否为付费用户
                    userInfor.setWechatimgurl(resultbean.getString("wechatimgurl"));   //微信地址

                    //xkj 2016-12-20 广告用的管辖区域
                    userInfor.setManagerzoneno(resultbean.getString("managerzoneno")); //管辖区域
                    // 2017-03-24 是否开通快速登录
                    userInfor.setIsopenmobilelogin(resultbean.getString("isopenmobilelogin"));
                    // 2017-04-19 所属公司 管辖区域
                    userInfor.setCompanyname(resultbean.getString("companyname"));
                    userInfor.setManagerzonename(resultbean.getString("managerzonename"));
                    // 2017-06-09 增加token
                    LoadDataManager.getInstance().setToken(resultbean.getString("apptoken"));
                    // 2017-06-13 增加判断是否有开屏广告
                    userInfor.setIsindexadsshow(resultbean.getString("isindexadsshow"));

                    CacheUtils.setString(Control.USERID, userid);

                    //设置广告需要的区域
                    toSetAdmanagerzoneno();

                    //检查是否升级vip
                    checkVip(flag, context, callback, resultdesc);

                    //初始化极光推送的alias
                    // toInitJpush(context,userid);

                    if (flag == REGIST) {
                        setRegistRelogin(context, requestBean);
                    }
                    if (flag == LOGIN) {
                        setReLoginMessage(context, requestBean);
                    }
                    if (flag == REGIST_BYPHONE || flag == LOGIN_BYPHONE) {
                        String fingerprint = resultbean.getString("fingerprint");
                        setPhoneLoginMessage(context, username, fingerprint);
                    }

                    //账号的统计
                    MobclickAgent.onProfileSignIn(UserInfor.getInstance().getUserid());

                } else {
                    callback.onFail(resultdesc);
                }

                //添加谷歌分析



            }
        } catch (Exception e) {
            e.printStackTrace();
            callback.onFail("解析登录返回数据失败");
        }
    }

    /**
     * 检查是vip等级是否需要升级vip
     * 检查密码是否是888888
     */
    private void checkVip(int flag, Context context, UserCallback callback, String desc) {
        UserInfor.getInstance().setRequestpassword(mPassword);
        if ("888888".equals(mPassword)) { //密码为888888的用户要先修改密码
            Bundle bundle = new Bundle();
            if (LOGIN == flag) {
                bundle.putString(SafetyTipsActivity.COME_PAGE, SafetyTipsActivity.LOGIN);
            }
            Intent safeTips = new Intent(context, SafetyTipsActivity.class);
            if (LOGIN == flag) {
                safeTips.putExtra(SafetyTipsActivity.COME_PAGE, SafetyTipsActivity.LOGIN);
            } else if (LOGIN_BYPHONE == flag) {
                safeTips.putExtra(SafetyTipsActivity.COME_PAGE, SafetyTipsActivity.LOGIN_BYPHONE);
            } else {
                safeTips.putExtra(SafetyTipsActivity.COME_PAGE, SafetyTipsActivity.LOGIN_ELSE);
            }
            context.startActivity(safeTips);
            callback.onSuccess(UserCallback.CHANGE_PASSWORD, desc);
            return;
        }
        //取消跳转到开通快捷登录页面   20170418
//        if ("0".equals(UserInfor.getInstance().getIsopenmobilelogin())) { //没有开通快捷登录的用户提示开通快捷登录
//            Intent intent = new Intent(context, OpenLoginActivity.class);
//            intent.putExtra(OpenLoginActivity.EXTRA_PARAMS, true);
//            if (flag == LAUNCH || flag == GUIDE) {
//                intent.putExtra(OpenLoginActivity.LOGIN_PAGE_FROM, OpenLoginActivity.AUTO_LOIN);
//            }else if(flag == LOGIN){
//                intent.putExtra(OpenLoginActivity.LOGIN_PAGE_FROM, OpenLoginActivity.NON_AUTO_LOGIN);
//            }
//            context.startActivity(intent);
//            callback.onSuccess(UserCallback.OPEN_LOGIN_PAGE, desc);
//            return;
//        }
        //没有vip的 取消开始就跳转到vip 20170525
//        if (UserInfor.getInstance().getViptype() == 1) { //vip没有升级的用户提示升级vip
//            Intent intent = new Intent(context, VipDescriptionActivity.class);
//            intent.putExtra(VipDescriptionActivity.MODE, VipDescriptionActivity.LOGIN);
//            context.startActivity(intent);
//            callback.onSuccess(UserCallback.VIP, desc);
//            ActivityUtil.finishAllAcivity();
//        } else {
//            callback.onSuccess(UserCallback.HOME_PAGE, desc);
//        }
        callback.onSuccess(UserCallback.HOME_PAGE, desc);
    }


    /**
     * 设置广告所需要的管辖区域
     */
    private void toSetAdmanagerzoneno() {
        ADManager.getInstance().setManagerzoneno(UserInfor.getInstance().getManagerzoneno(), UserInfor.getInstance().getUserid());
    }

    /**
     * 用户登录后
     * 首先设置应用id，然后设置用户id
     */
    public void onUserSignIn() {

    }


//    /**
//     * 初始化极光推送的alias
//     */
//    private void toInitJpush(Context context,String userId){
//        JPushInterface.setAlias(context, userId, new TagAliasCallback() {
//            @Override
//            public void gotResult(int i, String s, Set<String> set) {
//                PrintLog.d(TAG,"initJpush:"+i);
//            }
//        });
//    }

}